from django.shortcuts import render, redirect
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework.generics import ListAPIView
from django_redis import get_redis_connection
from tenthpower.utils.fastdfs import FastUploadImage
from rest_framework.response import Response
from .models import SpitImageUrl
from django.http import HttpResponse
from django.conf import settings
from rest_framework_mongoengine.viewsets import ModelViewSet
from rest_framework.views import APIView
from .serializer import *


# 吐槽列表
# 获取吐槽列表数据/发布吐槽
# GET Path： /spit/
# POST Path： /spit/
class SplitListCreateApiView(ModelViewSet):
    serializer_class = SpiltModelSerializer
    queryset = Spit.objects.all()
    permission_classes = [IsAuthenticatedOrReadOnly,]

    # 不同请求,分发不同的后端认证
    # 视图集中,请求对象self.request.method
    def get_authenticators(self):
        if self.request.method == "GET":
            return []
        return super().get_authenticators()

    # 收藏或取消收藏
    # PUT Path： /spit/{id}/collect/
    def update(self, request, *args, **kwargs):
        # 逻辑:获取用户id, 和点击收藏的吐槽id,判断吐槽id是否存在,存在则删除,不存在则添加
        user_id = request.user.id
        # 路径参数从self.kwargs中获取
        spit_id = self.kwargs.get('pk')
        spit = Spit.objects.get(id=spit_id)
        conn = get_redis_connection('collect')
        collects = conn.smembers(f'collect{user_id}')
        if spit_id.encode() in collects:
            conn.srem(f'collect{user_id}', spit_id)
            spit.collected = False
            spit.save()
            return Response({
                'message': '取消收藏成功',
                'success': "true"
            })
        conn.sadd(f'collect{user_id}', spit_id)
        spit.collected = True
        spit.save()
        return Response({
            'message': '收藏成功',
            'success': "true"
        })


# 富文本编辑器上传图片
# POST Path: /upload/common/
class UploadPicture(APIView):
    def post(self, request):
        # 富文本编辑器,传输数据也是以表单形式传递
        # 可以通过FILES.get()获取图片对象
        # http://127.0.0.1:8000/upload/common/?CKEditor=editor2&CKEditorFuncNum=1&langCode=zh-cn
        # 富文本编辑器的路径参数
        content = request.FILES.get('upload')
        callback = request.GET.get('CKEditorFuncNum')
        # 调用fastdfs封装的全局函数
        res = FastUploadImage(content)
        # 如果上传失败
        if res['Status'] != 'Upload successed.':
            return HttpResponse(status=403)
        # FastDFS返回图片标识
        image_url = res["Remote file_id"]

        # 一定要登录才能匿名发送,将图片url保存至mysql
        spit = SpitImageUrl.objects.create(image=image_url)
        #  来源地址
        from_address = request.META['HTTP_REFERER']
        # 右往左,分割路径将  http://127.0.0.1:8080/spit-submit.html
        # 分割成 http://127.0.0.1:8080
        from_address = from_address[:from_address.rfind('/'):]
        # 返回重定向格式
        # http://127.0.0.1:8080/upload_success.html?image_url=http://192.168.203.153:8888/group1/M00/00/02/wKjLmV-Hr8eALcERAADYK4ex7Tc1786436&CKEditorFuncNum=1
        ret_url = from_address + '/upload_success.html?image_url=' + settings.FDFS_BASE_URL + image_url + '&CKEditorFuncNum=' + callback
        return redirect(ret_url)


# 点赞或取消点赞
# PUT Path： /spit/{id}/updatethumbup/
class UpdateThumbupViewSet(ModelViewSet):
    queryset = Spit.objects.all()
    serializer_class = SpiltModelSerializer

    def update(self, request, *args, **kwargs):
        # 获取用户id，和点赞的id，判断id是否存在.
        user_id = request.user.id
        spit_id = self.kwargs.get('pk')
        spit = Spit.objects.get(id=spit_id)
        conn = get_redis_connection('hasthumbup')
        thumbups_id = conn.smembers(f'thumbup{user_id}')
        # 是否点赞判断
        if spit_id.encode() in thumbups_id:
            conn.srem(f'thumbup{user_id}', spit_id)
            spit.hasthumbup = False
            spit.thumbup -= 1
            spit.save()
            return Response({'success': 'true', 'message': '取消点赞成功'})
        conn.sadd(f'thumbup{user_id}', spit_id)
        spit.hasthumbup = True
        spit.thumbup += 1
        spit.save()
        return Response({'success': 'true', 'message': '点赞成功'})


# 吐槽详情
# 获取吐槽详情数据
# GET Path： /spit/{id}/
class SpitdetailModelViewSet(ModelViewSet):
    serializer_class = SpiltModelSerializer
    queryset = Spit.objects.all()


# 获取吐槽评论
# GET Path： /spit/{id}/children/
class CommentSpitListApiView(ListAPIView):
    serializer_class = SpiltModelSerializer
    queryset = Spit.objects.all()

    # 吐槽的评论也为吐槽,需要过滤查询集
    def get_queryset(self):
        parent_id = self.kwargs.get('pk')
        return self.queryset.filter(parent=parent_id)
